import json, re, random, logging
from django.views import View
from django_redis import get_redis_connection
from django.http import JsonResponse, HttpResponse
from myhome.libs.captcha.captcha import captcha
from myhome.libs.yuntongxun.ccp_sms import CCP

logger = logging.getLogger('django')


class ImageCodeView(View):

    def get(self, request):
        '''
        生成图像验证码
        '''
        # 1. 提取参数
        cur = request.GET.get('cur')
        # 2.校验参数
        if not re.match(r'^\w{8}(-\w{4}){3}-\w{12}$', cur):
            return JsonResponse({
                'code': '4000',
                'errmsg': 'cur不符合格式！'
            })
        # 3. 调用工具类生成图形验证码
        text, image = captcha.generate_captcha()
        print('图形验证码是:%s' % text)
        # 4. 保存验证码到redis数据库
        try:
            conn = get_redis_connection('verify_code')
            # setex(name,time,value): 以键值对的形式保存，time:保存时间
            conn.setex('img_%s' % cur, 300, text)
        except Exception as e:
            logger.error(e)
            return HttpResponse('图像验证码保存失败')
        # 5. 构建响应返回
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):

    def post(self, request):
        '''
        生成短信验证码
        :param request: 请求对象
        :return: 短信验证码
        '''

        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        id = data.get('id')  # 图形验证码编号
        text = data.get('text')  # 图片验证码内容

        # 1. 校验参数
        if not all([mobile, id, text]):
            return JsonResponse({
                'errno': '4103',
                'errmsg': '参数缺失'
            })
        # 1.1 读取redis数据库的图像验证码
        conn = get_redis_connection('verify_code')
        image_from_redis = conn.get('img_%s' % id)
        if not image_from_redis:
            return JsonResponse({
                'errno': '4004',
                'errmsg': '图像验证码过期！'
            })

        # 1.2 判断图形验证码是否过期
        if text.lower() != image_from_redis.decode().lower():
            return JsonResponse({
                'errno': '4004',
                'errmsg': '图形验证码输入错误'
            })
        # 1.3 判断60s内是否发送过短信
        try:
            conn.delete('img_%s' % id)
            flag = conn.get('sms_flag_%s' % mobile)
            if flag:
                return JsonResponse({
                    'errno': '4000',
                    'errmsg': '请勿重复发送短信'
                })
        except Exception as e:
            logger.error(e)
            return JsonResponse({

            })
        # 2. 使用云通信发送短信
        # 2.1 生成6位数随机码
        sms_code = '%06d' % random.randint(0, 999999)
        print('短信验证码:', sms_code)
        # 2.2 把生成的随机码存到数据库中
        p1 = conn.pipeline()
        try:
            p1.setex('sms_%s' % mobile, 300, sms_code)
            # 设置标识位
            p1.setex('sms_flag_%s' % mobile, 60, '1')
            p1.execute()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'errno': '4004',
                'errmsg': '短信验证码保存失败'
            })
        # 2.3 调用云通信发送短信
        CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # 3.构建响应返回
        return JsonResponse({
            'errno': '0',
            'errmsg': '发送成功'
        })
